##
## Webcontrol.py 
##
## Offers web stuff for web2Admin script.
## (ie create virtual host, web, etc.)
##
## Author: Shannon Eric Peevey <speeves@erikin.com>, 17 Jan 2004
##
import os, re, string
from shutil import copy
import Analog
try:
    import Ldap
except ImportError:
    pass

class ApacheFunc:
    """Offers web creation, virtual host creation, web server functionality for web2Admin script.
    (ie create web, create vhost, restart apache)"""

    
    def EnableDisableApacheVHostText(self):
        """ Text which describes a2ensite/a2dissite usage """
        print "You may enable/disable single sites, or multiple sites using file globbing"
        print
        print "single site: "
        print "www_erikin_com.conf"
        print
        print "multiple sites w/ globbing: "
        print "*hr*"
        print "Will enable/disable hr_erikin_com.conf/www_hr_erikin_com_ssl.conf/www_hr_erikin_com_publish.conf"
        print
        print "multiple sites w/out globbing: "
        print "www_tams_erikin_com.conf www_erikin_com_publish.conf facilities_erikin_com_ssl.conf"
        print

    def DisableApacheVHost(self, config, site=""):
        """ Disable Apache Confs on the admin machine / if using a split configuration """
        self.EnableDisableApacheVHostText()

        # do we want a listing of enabled vhosts?
        view = raw_input("\nPrint List of Enabled VHosts? (y/n) [n] ")
        if view == "":
            view = "n"

        if view == "y":
            dirList = "ls " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostEnabledConfDir"]
            print dirList
            os.system(dirList)
            
        while site == "":
            site = raw_input("Sitename? ")

        try:
            disableApacheVHostCommand = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["disableSite"] + " " + site
            cmdOutput = os.system(disableApacheVHostCommand)
        except:
            print "Disabling command failed: Please run " + disableApacheVHostCommand
            print "from the command line to debug"


    def EnableApacheVHost(self, config, site=""):
        """ Enable Apache Confs on the admin machine / if using a split configuration"""
        self.EnableDisableApacheVHostText()

        # do we want a listing of enabled vhosts?
        view = raw_input("\nPrint List of VHosts? (y/n) [n] ")
        if view == "":
            view = "n"

        if view == "y":
            dirList = "ls " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostAvailableConfDir"]
            print dirList
            os.system(dirList)

        while site == "":
            site = raw_input("Sitename? ")

        try:
            enableApacheVHostCommand = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["enableSite"] + " " + site
            cmdOutput = os.system(enableApacheVHostCommand)
        except:
            print "Enabling command failed: Please run " + enableApacheVHostCommand
            print "from the command line to debug"

        

    def CreateVHost(self, config, errorObject, utilityObject):
        """ Creates an apache virtual host """

        # Explanation of isVHost variable
        #
        # isVHost == 0 then this is for a web
        # isVHost == 1 then this is for a virtual host
        # if isVHost == 2 then this is for a virtual with a nested root inside another virtual host
        #
        # Initialize these variables
        #
        
        vHostWebroot = ""
        nestedVHostWebName = ""
        vHostLog = ""
        sslCertInPlace = ""
        networkInterfaces = ""
        isVHost = 1

        ## DEBUGGING (allows us to step through this application)
        if config['General']["debugLevel"] == '5':
            import pdb; pdb.set_trace()

        # print the list of existing vhosts and their webroots
        self.PrintVhost(config, utilityObject)
        
        #
        # If the vHost has a webroot that is nested in another vHost:
        #
        #    existing host         = www.example.com
        #    existing host webroot = /var/www
        #    new vHost             = www.example2.com
        #    new vHost webroot     = /var/www/example2
        #
        # 1. We need to get the full URL to the nested directory from the user
        # 2. Split the URL on the forward slash (www.example.com/example2 becomes:
        #       list = ['www.example.com', 'example2']
        # 3. Search the VHost.txt file for the existing web and webroot
        # 4. Assign the webroot of the existing web to vHostWebroot
        #       (vHostWebroot == the root of the website (ie /var/www/example2)
        # 5. 
        #
        vHostNestedHost = raw_input("Does the DocumentRoot for this vHost already exist? (y/n) [n] ")
        if vHostNestedHost == "":
            vHostNestedHost = "n"
            
        if vHostNestedHost == "y":
            vHostNestedWebroot = raw_input("What is the URL to the existing vHost and website? (ie www.example.com/subweb) ")
            splitVhostNestedWebroot = re.split('/', vHostNestedWebroot)
            ## DEBUGGING
            if config['General']["debugLevel"] == '5':
                print vHostNestedWebroot
                
            slashFindRE = string.find(vHostNestedWebroot, '/')
            # search VHost.txt for webroot
            # grab the list of virtual hosts
            vHostTextList = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"]) 
            for eachline in vHostTextList:
                if eachline[0] == "#" or eachline[0] == '\n':
                    continue
                else:
                    splitVhostTextLine = re.split(':', eachline)
                    splitVhostTextLine2 = splitVhostTextLine[2]
                    ## DEBUGGING
                    if config['General']["debugLevel"] == '5':
                        print "splitVhostTextLine = ", splitVhostTextLine
                        print "splitVhostTextLine2 = ", splitVhostTextLine2
                        
                    if splitVhostTextLine2[:-1] == splitVhostNestedWebroot[0]:
                        vHostWebroot = splitVhostTextLine[1]

            ## DEBUGGING (allows us to step through this application)
    	    if config['General']["debugLevel"] == '5':
        	import pdb; pdb.set_trace()

	    # if slashFindRE == "-1" set nestedVHostWebName to empty string
	    if slashFindRE == -1:
		nestedVHostWebName = ""
	    else:
		nestedVHostWebName = vHostNestedWebroot[slashFindRE:]

            isVHost = 2
            ## DEBUGGING
            if config['General']["debugLevel"] == '5':
                print "isVHost == ", isVHost


        #
        # Get the FQDN for the vHost that they want to create.
        #     (ie www.example.com)
        # Then substitute the '.'s with '_', then get a directory listing
        # of the base root (ie /var/www), and check to see if the
        # webroot already exists.  If it does, offer to use an alternate
        # webroot
        #
        # if the fqdn was passed in from the command line, then use it to set 
        if config["Options"]["fqdn"] == "":
            vHostName = raw_input("What is the FQDN for the new Virtual Host? (ie www.erikin.com) ")
        else:
            vHostName = config["Options"]["fqdn"]
        vHostFileName = re.sub('\.', '_', vHostName)
            
        if vHostWebroot == '':
            # split the FQDN to do some shorthand for the user
            # and offer Other to allow them to specify a different web
            if isVHost == 2:
                vHostFileName = splitVhostNestedWebroot[0]
                vHostFileName = re.sub('\.', '_', vHostFileName)
            else:
                vHostWebroot = vHostFileName
                
            filelist = os.listdir(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"])
            for folder in filelist:
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print 'config["Apache"]["vHostRoot"] == ', config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"]
                    print 'This is the current folder for the directory list from config["Apache"]["vHostRoot"]', folder
                    
                if vHostWebroot == folder:
                    print "This folder seems to exist..."
                    vHostWebroot = raw_input("Please, specify an alternate webroot here: (ie newwebroot) ")

        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostIpaddress"] == "":
            vHostIpaddress = raw_input("What is the IP address for the new vHost? (ie 123.456.678.3) ")
        else:
            vHostIpaddress = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostIpaddress"]

        ## DEBUGGING
        if config['General']["debugLevel"] == '1':
            print "The vHost you chose was", vHostName
            print "The FQDN you chose is", vHostName
            print "The Webroot you chose is", vHostWebroot
            print "The nested web location is", nestedVHostWebName
            print "Your logfiles and conf files will be prefixed with ", vHostFileName

        ## Begin of Apache Section
        #
        # Create the apache vhost conf files for ports 80, 443, 8080
        #
        # 1. Set the location for the vHost:80, vHost:443, and vHost:8080
        # 2. Create temporary dictionary to facilitate creation of conf files
        # 3. Ask if they want an ssl conf, then grab the text from the skel files
        # 4. Check every line of text for variables and replace them with the value in the dict
        # 5. Write the modified text into the appropriate vHost:80, 443, and 8080
        # 6. Check if they have already moved the crt and key into place, if so, enable ssl site,
        #    if not don't enable ssl conf.
        # 7. Add NameVirtualHost directive into apache conf file
        # 8. Adds the Listen directive in the ports.conf file
        # 9. Call NestedVhostCreation() which:
        #    a) makes the _private, stats and stats/images directory
        #    b) copies analogImage to stats/images
        #    c) chowns the stats dir to webUser and webGroup
        #    d) create htaccess and .htaccess2 files
        #    e) mv htaccess files to webroot and stats dir
        #10. Append vHost information to conf/vHost.txt file 
        #11. Copy htgroup.skel to apache access directory htgroup.vHost
        #12. Enable vhost:80 and vhost:8080.
        #13. If createApacheSslConf and sslCertInPlace and networkInterfaces == 'y':
        #        enable vhost:443.  Else: user needs to manually enable vhost:443 from the command line.
        #14. Restart Apache
        #15. Chown the logfiles to config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] and config['Apache']["webGroup"]
        
        # 1. Set the location for the vHost:80, vHost:443, and vHost:8080
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
            apacheConf_location = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + ".conf"
            apachePublishConf_location = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + "_publish.conf"
            apacheSslConf_location = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + "_ssl.conf"
        else:
            # need to add the text to the main httpd.conf file
            apacheConf_location = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfDir"] + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheGlobalConf"]

        # 2. Create temporary dictionary to facilitate creation of conf files
        ### TODO: this needs to be pulled out of here, and dynamically generated
        ### It is used to replace variable names in the apache_conf*.skel files and is
        ### passed to UtilityObject.CheckSkelLineforVariable()
        confDict = {
            "vHostName":vHostName,
            "vHostIpaddress":vHostIpaddress,
            "vHostPort":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPort"],
            "vHostSslPort":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostSslPort"],
            "vHostPublishPort":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPublishPort"],
            "vHostRoot":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"],
            "vHostWebroot":vHostWebroot,
            "vHostNestedHost":vHostNestedHost,
            "vHostIpaddress":vHostIpaddress,
            "nestedVHostWebName":nestedVHostWebName,
            "vHostFileName":vHostFileName,
            "logPath":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["logPath"],
            "pathToPasswordFile":htgroupDict["pathToPasswordFile"],
            "pathToHtgroupFile":htgroupDict["pathToHtgroupFile"],
            "ldapHostname":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapHostname"],
            "ldapPort":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapPort"],
            "ldapProtocol":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapProtocol"],
            "ldapBasedn":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapBasedn"],
            "ldap_UserAttr":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapUserAttr"],
            "ldapUser":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["apacheLdapUser"],
            "ldap_UserPassword":config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["apacheLdapUserPassword"],
            "wsconfigNumber":config['Coldfusion']['Server' + config['Session']['Coldfusion']['CurrentServer']]["wsconfigNumber"],
            "cfIpAddress":config['Coldfusion']['Server' + config['Session']['Coldfusion']['CurrentServer']]["cfIpAddress"],
            "cfPort":config['Coldfusion']['Server' + config['Session']['Coldfusion']['CurrentServer']]["cfPort"],
        }            

        ## DEBUGGING (allows us to step through this application)
        if config['General']["debugLevel"] == '5':
            import pdb; pdb.set_trace()
            
        # 3. Ask if they want an ssl conf, then grab the text from the skel files
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["defaultCreateSsl"] == "0":
            createApacheSslConf = raw_input("\nWould you like an SSL conf as well? (y or n) [y] ")
            if createApacheSslConf == "":
                createApacheSslConf = "y"
        else:
            createApacheSslConf = "y"
        
        # first, create the apache conf and ssl conf
        # grab the skel file contents
        apacheConfLines = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["confSkel"])
        apachePublishConfLines = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pubConfSkel"])
        
        # 4. Check every line of text for variables and replace them with the value in the dict
        apacheConfCreate = utilityObject.CheckSkelLineforVariable(config, confDict, apacheConfLines)
        apachePublishConfCreate = utilityObject.CheckSkelLineforVariable(config, confDict, apachePublishConfLines)

        # 5. Write the modified text into the appropriate vHost:80, 443, and 8080
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
            apacheConf = open(apacheConf_location, 'w')
            apacheConf.write(apacheConfCreate)
            apacheConf.close()
            # write the new publish conf file
            apachePublishConf = open(apachePublishConf_location, 'w')
            apachePublishConf.write(apachePublishConfCreate)
            apachePublishConf.close()
        else:
            ### add the conf lines to the httpd.conf
            # add the port 80 VirtualHost
            self.AddVirtualHostConfToApacheConf(config, confDict, apacheConfCreate, utilityObject)
            # add the port 8080 VirtualHost
            self.AddVirtualHostConfToApacheConf(config, confDict, apachePublishConfCreate, utilityObject)
            
        # second, create apachesslconf if the user responded 'y'
        if createApacheSslConf == 'y':
            apacheSslConfLines = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["sslConfSkel"])
            apacheSslConfCreate = utilityObject.CheckSkelLineforVariable(config, confDict, apacheSslConfLines)

            # write the new ssl conf file
            if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
                apacheSslConf = open(apacheSslConf_location, 'w')
                apacheSslConf.write(apacheSslConfCreate)
                apacheSslConf.close()
            else:
                ### add the conf to main httpd.conf file
                # add the port 443 VirtualHost
                self.AddVirtualHostConfToApacheConf(config, confDict, apacheSslConfCreate, utilityObject)
                
            # 6. Check if they have already moved the crt and key into place, if so, enable ssl site,
            #    if not don't enable ssl conf.
            print "\nBefore this script will enable SSL (:443) vHosts, you need to"
            print "mv the ssl.crt and ssl.key into /etc/apache2/ssl.crt/ and "
            print "/etc/apache2/ssl.key/.  They must be in the format: FQDN.key and"
            print "FQDN.crt.  For example:\n"
        
            print "/etc/apache2/ssl.crt/www.example.com.crt"
            print "/etc/apache2/ssl.key/www.example.com.key\n"
        
            print "You also need to make sure that you have added the appropriate "
            print "IP Address to your /etc/network/interfaces file.  You must have "
            print "a different IP Address for each SSL vHost, unless you have a "
            print "* SSL certificate for a complete domain."
        
            print "If you have done all of these steps, answer yes here.  If you "
            print "have not completed these two steps, or are not sure, answer no.\n"

            if createApacheSslConf == 'y':
                if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["defaultSslCertInPlace"] == "1":
                    sslCertInPlace = raw_input("Have you moved the SSL certificates into place? (y or n) [y] ")
                    if sslCertInPlace == "":
                        sslCertInPlace = "y"
                else:
                    sslCertInPlace = "y"
                    
                if sslCertInPlace == 'y':
                    if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["defaultAddIpToNetworkInterfaces"] == "1":
                        networkInterfaces = raw_input("Have you added the new IP address into the /etc/network/interfaces file? (y or n) [y] ")
                    if networkInterfaces == '':
                        networkInterfaces = "y"
                else:
                    networkInterfaces = "y"
                    
        # 7. Add NameVirtualHost directive into apache conf file
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
            self.AddNameVirtualHostToApacheConf(config, vHostIpaddress, createApacheSslConf, sslCertInPlace, networkInterfaces, utilityObject)

        # 8. Adds the Listen directive in the ports.conf file
        self.AddPortsToApacheConf(config, vHostIpaddress, createApacheSslConf, sslCertInPlace, networkInterfaces, utilityObject)
        
        # 9. Call NestedVhostCreation() which:
        #    a) makes the _private, stats and stats/images directory
        #    b) copies analogImage to stats/images
        #    c) chowns the stats dir to webUser and webGroup
        #    d) create htaccess and .htaccess2 files
        #    e) mv htaccess files to webroot and stats dir
        # 
        ## DEBUGGING (allows us to step through this application)
        if config['General']["debugLevel"] == '5':
            import pdb; pdb.set_trace()

        self.NestedVhostCreation(config, utilityObject, confDict, isVHost)

        #10. Append vHost information to conf/vHost.txt file 
        self.AddVHostList(config, vHostName, vHostFileName, vHostWebroot, utilityObject)

        #11. Copy htgroup.skel to apache access directory htgroup.vHost
        if not os.path.isfile(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheAccessDir"] + 'htgroup.' + vHostWebroot):
            copy(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["htgroupSkel"], config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheAccessDir"] + 'htgroup.' + vHostWebroot)
        
        #12. Enable vhost:80 and vhost:8080
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
            enablePort80 = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["enableSite"] + " " + apacheConf_location
            enablePort8080 = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["enableSite"] + " " + apachePublishConf_location
        
        #13. If createApacheSslConf and sslCertInPlace and networkInterfaces == 'y':
        #        enable vhost:443.  Else: user needs to manually enable vhost:443 from the command line.
        #
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
            if createApacheSslConf == 'y' and sslCertInPlace == 'y' and networkInterfaces == 'y':
                enablePort443 = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["enableSite"] + " " + apacheSslConf_location

        ### Nov. 21, 2006 - this is moved to the end of vhost create, so that we can enable vhosts
        ### before restarting apache...
        # 14. Restart Apache
        #self.RestartApache(apacheDict)

        # 15. Chown the logfiles to config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] and config['Apache']["webGroup"]
        chownWeb = config['General']["binPath"] + "chown -R " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] + "." + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webGroup"] + " " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["logPath"]
        if config['General']["debugLevel"] == '1':
            print chownWeb
        os.system(chownWeb)
        ## End of Apache Section
            
        ## Begin of Stats Section
        #
        # Create the Analog Stats file for the Virtual Host being created
        #
        # 1. Call CreateAnalogSkel() to create the modified vhost.cfg in analogConf.
        # 2. ??? is this needed ???  Call AddVHostToStatsFile() to append the vhost information to vhost.txt file
        #    It appears that 10. from the apache section already does this...
        #
        if config['Analog']["useAnalog"] == "1":
            stats = Analog.AnalogFunc()
            if isVHost == '1':
                stats.CreateAnalogSkel(config, vHostName, vHostFileName, vHostWebroot, isVHost, utilityObject)
            else:
                stats.CreateAnalogSkel(config, vHostName, vHostFileName, vHostWebroot, isVHost, utilityObject, nestedVHostWebName[1:])
                
            # stats.AddVHostToStatsFile(config, vHostName, vHostWebroot, vHostFileName)
            del stats
        ## End of Stats Section


        # if vhost is not a nested vhost run LDAP queries
        if isVHost == 1:
            ## Begin of LDAP Section
            #
            # Create the OU for vhost, admin groups
            #
            # 1. Create LdapObject
            # 2. Connect to LDAP Server
            # 3. Create vHost Organization Unit
            # 4. Create admin group under vHost Organizational Unit
            # 5. Add admin users to admin group
            # 6. Disconnect from LDAP Server
            #
            if config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["useLdap"] == "1":
                # 1. Create LdapObject
                ldapObject = Ldap.LdapFunc()
                # 2. Connect to LDAP Server
                # ldapConn = ldapObject.Connect(ldapDict)


                ## DEBUGGING (allows us to step through this application)
                if config['General']["debugLevel"] == '5':
                    import pdb; pdb.set_trace()

                # 3. Create vHost Organization Unit
                create = ldapObject.CreateOU(config, vHostWebroot)
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print create
                
                # 4. Create admin group under vHost Organizational Unit
                for group in defaultGroups:
                    create2 = ldapObject.CreateGroup(config, vHostWebroot, group)
                    ## DEBUGGING
                    if config['General']["debugLevel"] == '1':
                        print "CreateGroup returned ", create2

                    ## 9/29/06 we have a new centralized storage for the admin group
                    ## so we no longer need to create new admin groups for every OU that we create
                    ## -- deprecated --
                    # 5. Add admin users to admin group
                    #if group == 'admin':
                    #    for user in adminUsers:
                    #        userAttrs = []
                    #        userAttrs = ldapObject.UserAttrs(config,  vHostWebroot, user)
                    #        dn = ldapObject.CreateGroupDN(config,  vHostWebroot, group)
                    #        ldapObject.LdapModifyObject(config,  dn, userAttrs)

                # 6. Disconnect from LDAP Server
                # ldapObject.Disconnect(ldapConn)
            ## End of LDAP Section

        # if apache is using a split configuration - enable/disable vhost...?
        if config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["splitConfig"] == "1":
            enableDisableVhost = raw_input("Would you like to enable the virtual host? ([y]/n) ")
            if enableDisableVhost == "":
                enableDisableVhost = "y"

            if enableDisableVhost == "y":
                site = vHostFileName + "*"
                self.EnableApacheVHost(config, site)

        # 14. Restart Apache
        restartApache = raw_input("Restart Apache? ([y]/n) ")
        if restartApache == "":
            restartApache = "y"
        if restartApache == "y":
            self.ApacheCtl(config)
        else:
            print
            print "You will need to restart apache manually for any changes to take effect."
            print

            

    def CreateWeb(self, config, errorObject, utilityObject):        
        """ Creates an apache web inside of a virtual host """
        isVHost = 0
        vHostWebroot2 = "";

        ## DEBUGGING (allows us to step through this application)
        if config['General']["debugLevel"] == '5':
            import pdb; pdb.set_trace()
        # if fqdn == "" then we need to get the vhost
        if config["Session"]["fqdn"] == "" or config["Session"]["fqdn"] is None:
            # print out the list of vhosts, if the user would like
            self.PrintVhost(config, utilityObject)
            #print "\nChoose from this list of Virtual Hosts:\n"
            #self.FormattedSplitURLWebroot(config, vHostTextList)
            vHostName = raw_input("What virtual host will this web be in? (FQDN) ")
        else:
            vHostName = config["Session"]["fqdn"]

        # if subweb == "" then we need to get the subweb name
        if config["Session"]["subweb"] == "" or config["Session"]["subweb"] is None:
            webName = raw_input("What is the name of the new web? ")
        else:
            webName = config["Session"]["subweb"]
        print "The name you chose is", webName

        # grab the list of virtual hosts
        vHostTextList = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"])

        # find the webroot
        for eachline in vHostTextList:
            if eachline[0] == '#' or eachline[0] == '\n':
                continue
            else:
                ## DEBUGGING (allows us to step through this application)
                if config['General']["debugLevel"] == '5':
                    import pdb; pdb.set_trace()

                # TODO: vHostWebroot and vHostFileName are never initialized
                #       if the vhost in VHostName is not in the conf/*/VHost.txt file
                eachline1 = re.split(':', eachline)
                eachline2 = eachline1[2]
                if eachline2[-1]=='\n' : eachline = eachline2[:-1]
                if eachline == vHostName:
                    vHostWebroot = eachline1[1]
                    vHostFileName = eachline1[0]
                    break

        if config['General']["debugLevel"] == '1':
            print "The vHostName you chose was", vHostName
            print "The vHostWebroot is", vHostWebroot
            print "The vHostFileName is", vHostFileName
        
        # TODO: we need to copy the .htaccess2.bak file to .htaccess2 and then move it back again at the end...  Why?
        # I don't know.
        cp_htaccess = config['General']["binPath"] + "mv  " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/.htaccess2.bak " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/.htaccess2"
        cp_bak_htaccess = config['General']["binPath"] + "mv  " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/.htaccess2 " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/.htaccess2.bak"
        # here we are going to create a web 
        createWeb = config['General']["binPath"] + "mkdir -p " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName
        createWeb_private = config['General']["binPath"] + "mkdir -p " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName + "/_private"
        createWebImages = config['General']["binPath"] + "mkdir  " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName + "/images"
        chownWeb = config['General']["binPath"] + "chown -R " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] + "." + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webGroup"] + " " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName

        if config['General']["debugLevel"] == '1':
            print createWeb
            print createWeb_private
            print createWebImages
            print chownWeb
        os.system(createWeb)
        os.system(createWeb_private)
	os.system(createWebImages)
        os.system(chownWeb)


        # here is where we will copy the #htaccess.ctl file to the webs (/, and _private)
        htaccessLocationBrowse = []
        htaccessLocationBrowse.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName + "/.htaccess")
        htaccessLocationPublish = []
        htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName + "/.htaccess2")
        htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName + "/_private/.htaccess")        
        htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/" + webName + "/_private/.htaccess2")
        htaccessList = [htaccessLocationBrowse, htaccessLocationPublish]
        self.CreateHtaccess(config, utilityObject, vHostWebroot, isVHost, htaccessList, webName)

        ## chown the htaccess files with config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] & config['Apache']["webGroup"] 
        chownWebHtaccess = config['General']["binPath"] + "chown -R " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] + "." + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webGroup"] + " " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + vHostWebroot + "/.htaccess*"
        if config['General']["debugLevel"] == '1':
            print chownWebHtaccess
        os.system(chownWebHtaccess)
        
        
        # Do the stats stuff
        if config["Analog"]["useAnalog"] == "1":
            stats = Analog.AnalogFunc()
            stats.CreateAnalogSkel(config, vHostName, vHostFileName, vHostWebroot, isVHost, utilityObject, webName)
            del stats

        # create a connection to the ldap server
        # create instance and conn to ldap server
        if config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapHostname"] != "" and config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapPort"] != "":
            try:
                ldapObject = Ldap.LdapFunc()
        
                # connect to the server and bind
                # ldapConn = ldapObject.Connect(ldapDict)
                ## DEBUGGING
                if config['General']["debugLevel"] == '1':
                    print "vHostWebroot ==" + vHostWebroot
        
                # create the cn for the web under the vHost
                create2 = ldapObject.CreateGroup(config,  vHostWebroot, webName)
                ## DEBUGGING
                if config['General']["debugLevel"] == '1':
                    print "CreateGroup returned ", create2

                # ldap disconnect
                # ldapObject.Disconnect(ldapConn)
            except ImportError:
                print "LDAP is not enabled.  Add users through the Htgroup interface\n"
        else:
            ## DEBUGGING
            if config['General']["debugLevel"] == '5':
                if config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapHostname"] == "":
                    print 'config["Ldap"]["ldapHostname"] is not defined.  If you need LDAP support, please set this variable'
                elif config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["ldapPort"] == "":
                    print 'config["Ldap"]["ldapPort"] is not defined.  If you need LDAP support, please set this variable'
                
    def AddNameVirtualHostToApacheConf(self, config, vHostIpaddress, createApacheSslConf, sslCertInPlace, networkInterfaces, utilityObject):
        """ Adds the include line which will include the vHost.conf into the httpd.conf """
        # then, open httpd.conf and place a new line in the vHost section
        apacheConf = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfDir"] + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheGlobalConf"]
        alllines = utilityObject.GrabTextList(apacheConf)

        # Let's add them to a web in the htgroup file
        # we will loop it to help with the ease of use
        for eachline in alllines:
            existIp = "^NameVirtualHost " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPort"]
            checkExist = re.match(existIp, eachline)
            if checkExist != None:
                break
            holdingPattern = '^####DoNotRemove NameVirtualHost'
            m = re.match(holdingPattern, eachline)
            addEntry = 0
            if m != None:
                confIndex = alllines.index(eachline)
                alllines.remove(eachline)
                newInclude = "NameVirtualHost " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPort"] + "\n"                
                newInclude2 = "NameVirtualHost " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPublishPort"] + "\n"
                newLines = newInclude + newInclude2
                if createApacheSslConf == 'y' and sslCertInPlace == 'y' and networkInterfaces == 'y':
                    newInclude3 = "NameVirtualHost " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostSslPort"] + "\n"
                    newLines = newLines + newInclude3
                
                alllines.insert(confIndex, newLines)
                alllines.insert(confIndex + 1, eachline)
                addEntry = addEntry + 1
                break

	# rename the old file
	os.rename(apacheConf, apacheConf + '.bak')
	# open the destination file
	destination_file = open(apacheConf, 'w')
	# write lines into file
	destination_file.writelines(alllines)
	# close the destination file
	destination_file.close()


                
    def AddVirtualHostConfToApacheConf(self, config, confDict, confLines, utilityObject):
        """ Adds the include line which will add VirtualHost sections
            in the httpd.conf """
        # then, open httpd.conf and place a new line in the vHost section
        apacheConf = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfDir"] + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheGlobalConf"]
        alllines = utilityObject.GrabTextList(apacheConf)

        # Let's add them to a web in the htgroup file
        # we will loop it to help with the ease of use
        for eachline in alllines:
            holdingPattern = '^####DoNotRemove VirtualHost'
            m = re.match(holdingPattern, eachline)
            addEntry = 0
            if m != None:
                confIndex = alllines.index(eachline)
                alllines.remove(eachline)
                alllines.insert(confIndex, confLines)
                alllines.insert(confIndex + 1, eachline)
                addEntry = addEntry + 1
                break

	# rename the old file
	os.rename(apacheConf, apacheConf + '.bak')
	# open the destination file
	destination_file = open(apacheConf, 'w')
	# write lines into file
	destination_file.writelines(alllines)
	# close the destination file
	destination_file.close()



    def AddPortsToApacheConf(self, config, vHostIpaddress, createApacheSslConf, sslCertInPlace, networkInterfaces, utilityObject):
        """ Adds the include line which will include the vHost.conf into the httpd.conf """
        # then, open httpd.conf and place a new line in the vHost section
        portsConf = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfDir"] + config['Apache']["apachePortsConf"]
        alllines = utilityObject.GrabTextList(portsConf)

        # Let's add them to a web in the htgroup file
        # we will loop it to help with the ease of use
        for eachline in alllines:
            existPort = "^Listen " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPort"]
            checkExist = re.match(existPort, eachline)
            if checkExist != None:
                break
            holdingPattern = '^####DoNotRemove Listen'
            m = re.match(holdingPattern, eachline)
            addEntry = 0
            if m != None:
                confIndex = alllines.index(eachline)
                alllines.remove(eachline)
                addPort80 = "Listen " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPort"] + "\n"
                addPort8080 = "Listen " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostPublishPort"] + "\n"
                newLines = addPort80 + addPort8080
                if createApacheSslConf == 'y' and sslCertInPlace == 'y' and networkInterfaces == 'y':
                    addPort443 = "Listen " + vHostIpaddress + ":" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostSslPort"] + "\n"
                    newLines = newLines + addPort443
                
                alllines.insert(confIndex, newLines)
                alllines.insert(confIndex + 1, eachline)
                addEntry = addEntry + 1
                break

        if config['General']["debugLevel"] == '1':
            print alllines
            
        # rename the old file
        os.rename(portsConf, portsConf + '.bak')
        # open the destination file
        destination_file = open(portsConf, 'w')
        # write lines into file
        destination_file.writelines(alllines)
        # close the destination file
        destination_file.close()

    def NestedVhostCreation(self, config, utilityObject, confDict, isVHost):
        #  vHostWebroot, vHostNestedHost, vHostName, isVHost):
        """ This creates a virtual host conf where the vHost docroot already
        exists within another vHost """

        # Explanation of isVHost variable
        #
        # isVHost == 0 then this is for a web
        # isVHost == 1 then this is for a virtual host
        # if isVHost == 2 then this is for a virtual with a nested root inside another virtual host
        #
        
        # do not add or chown anything that is already existing
        if confDict["vHostNestedHost"] != "y":
            # Here we initialize the variables to create a web
            mkWebStatsDir = config['General']["binPath"] + "mkdir -p " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/stats/images"
            mkPrivateDir = config['General']["binPath"] + "mkdir -p " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/_private"
            # we don't need to run these one commands if we are on the www farm
            mkPhpmyadminDir = config['General']["binPath"] + "mkdir -p " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/phpmyadmin"


            chownWeb = config['General']["binPath"] + "chown -R " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webUser"] + "." + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["webGroup"] + " " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"]

            ## DEBUGGING
            if config['General']["debugLevel"] == '5':
                print "mkWebStatsDir == ", mkWebStatsDir
                print "mkPrivateDir == ", mkPrivateDir
                # we don't need to run these one commands if we are on the www farm
                print "mkPhpmyadminDir == ", mkPhpmyadminDir

                print "chownWeb == ", chownWeb
                
            # run the actual system calls to create the web
            os.system(mkWebStatsDir)
            os.system(mkPrivateDir)

            # we don't need to run these one commands if we are on the www farm
            os.system(mkPhpmyadminDir)

            os.system(chownWeb)

            htaccessLocationBrowse = []
            # here is where we will copy the #htaccess.ctl file to the webs (/, and _private)
            htaccessLocationBrowse.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/.htaccess")
            htaccessLocationBrowse.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/stats/.htaccess")

            htaccessLocationPublish = []
            # here is where we will copy the #htaccess.ctl file to the webs (/, and _private)
            htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/.htaccess2")
            htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/_private/.htaccess")
            htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/_private/.htaccess2")
            htaccessLocationPublish.append(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + confDict["vHostWebroot"] + "/stats/.htaccess2")

            htaccessList = [htaccessLocationBrowse, htaccessLocationPublish]
            
            self.CreateHtaccess(config, utilityObject, confDict["vHostWebroot"], isVHost, htaccessList)

    def CreateHtaccess(self, config, utilityObject, vHostWebroot, isVHost, htaccessList, webName = ''):
        """ Create the Htaccess file """
        # Explanation of isVHost variable
        #
        # isVHost == 0 then this is for a web
        # isVHost == 1 then this is for a virtual host
        # if isVHost == 2 then this is for a virtual with a nested root inside another virtual host
        #            

        # grab the skel file contents
        htaccessLines = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["htaccessSkel"])

        # split the htaccessList into parts
        #
        # htaccessList[0] = browse
        # htaccessList[1] = publish
        #

        for browsePublish in htaccessList:
            # htaccessLocation = ['/var/www/.htaccess']
            # write out the htaccessfiles

            # set a variable to designate browse/publish
            if htaccessList.index(browsePublish) == 0:
                browsePublishVar = 'browse'
                htaccessDict = {
                    "getPost":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["htaccessBrowseLimitExcept"]
                    }
            elif htaccessList.index(browsePublish) == 1:
                browsePublishVar = 'publish'
                htaccessDict = {
                    "getPost":config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["htaccessPublishLimitExcept"]
                    }

            for htaccessFileLocation in browsePublish:
                # Check every line of text for variables and replace them with the correct value
                htaccessFileModify = utilityObject.CheckSkelLineforVariable(config, htaccessDict, htaccessLines)
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print "htaccessFileLocation == ", htaccessFileLocation
                    print "htaccessFileModify == ", htaccessFileModify

                htaccessFileModify = htaccessFileModify.split('\n')
                newHtaccessFileModify = []
                # Now search the returned array to add the require lines
                for htaccessLine in htaccessFileModify:
                    ## DEBUGGING
                    if config['General']["debugLevel"] == '5':
                        # print "newHtaccessFileModify (before modify) == ", newHtaccessFileModify
                        print "htaccessLine == ", htaccessLine
                        print "defaultGroups == ", config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]['defaultGroups']

                    pattern = '^</LimitExcept>'
                    m = re.match(pattern, htaccessLine)
                    if m != None:
                        requireIndex = htaccessFileModify.index(htaccessLine)
                        for group in config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["defaultGroups"]:
                            newRequireLine = ''
                            groupLine = ''
                            ## DEBUGGING
                            if config['General']["debugLevel"] == '5':
                                print "group from defaultGroups == ", group
                                print "isVHost == ", isVHost
                                print "type(isVHost) == ", type(isVHost)
                                
                            # create the require line useLdap == '1' or useHtgroup == '1'
                            # htgroup: require entityName groupName
                            # ldap: require entityName cn= + groupName + vWebroot + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["containerBaseDn"]
                            if config['Ldap']["useLdap"] == '1':
                                # The first group must be the "admin" group. (index == 0).  We put a centralized group at the
                                # root of config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["containerBaseDn"] so that we can scale up quickly.
                                if config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]['defaultGroups'].index(group) == 0:
                                    newRequireLine = 'require ' + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["htaccessDefaultEntity"] + " cn=" + group + "," + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["containerBaseDn"]
                                else:
                                    if isVHost == 1:
                                        newRequireLine = 'require ' + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["htaccessDefaultEntity"] + " cn=" + group + ",ou=" + vHostWebroot + "," + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["containerBaseDn"]
                                    else:
                                        newRequireLine = 'require ' + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["htaccessDefaultEntity"] + " cn=" + webName + ",ou=" + vHostWebroot + "," + config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]["containerBaseDn"]

                                ## DEBUGGING
                                if config['General']["debugLevel"] == '5':
                                    print "(useLdap == '1') newRequireLine == ", newRequireLine
                                
                            else:
                                if config['Ldap']['Server' + config['Session']['Ldap']['CurrentServer']]['defaultGroups'].index(group) == 0:
                                    newRequireLine = 'require ' + config['Htgroup']['Server' + config['Session']['Htgroup']['CurrentServer']]["htaccessDefaultEntity"] + " " + group
                                else:
                                    if isVHost == 1:
                                        newRequireLine = 'require ' + config['Htgroup']['Server' + config['Session']['Htgroup']['CurrentServer']]["htaccessDefaultEntity"] + " " + group
                                    else:
                                        newRequireLine = 'require ' + config['Htgroup']['Server' + config['Session']['Htgroup']['CurrentServer']]["htaccessDefaultEntity"] + " " + webName
                                        
                                ## DEBUGGING
                                if config['General']["debugLevel"] == '5':
                                    print "else: newRequireLine == ", newRequireLine

                            newHtaccessFileModify.insert(requireIndex, newRequireLine)
                    else:
                        ## DEBUGGING
                        if config['General']["debugLevel"] == '5':
                            print "type(newHtaccessFileModify) (END) == ", newHtaccessFileModify
                            
                        newHtaccessFileModify.append(htaccessLine)
                        continue

                    newHtaccessFileModify.append(htaccessLine)
                    newHtaccessFileModify = "\n".join(newHtaccessFileModify)
                    ## DEBUGGING
                    if config['General']["debugLevel"] == '5':
                        print "newHtaccessFileModify (after modify) == ", newHtaccessFileModify

                    # write the new publish conf file
                    newHtaccessFile = open(htaccessFileLocation, 'w')
                    newHtaccessFile.write(newHtaccessFileModify)
                    newHtaccessFile.close()
                
                    # reinitialize the newHtaccessFileModify list
                    newHtaccessFileModify = []
                    
        
    def GrabTextList(self, file):
       """ Grab all the lines in a text file """
       sourceFile = open(file, 'r')
       alllines = sourceFile.readlines()
       sourceFile.close()

       return alllines

    def AddVHostList(self, config, vHostName, vHostFileName, vHostWebroot, utilityObject):
        """ Adds the necessary lines to the vHost.txt in the form:
        vHostAccessLog:vHostWebroot:vHostFqdn """
        alllines = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"])
        url = self.SplitVHostList(alllines)

        # Let's add them to a web in the htgroup file
        # we will loop it to help with the ease of use
        addEntry = 0
        for eachline in url:
            pattern = '^' + vHostName
            m = re.match(pattern, eachline)
            if m != None:
                addEntry = 0
                break
            else:
                addEntry = addEntry + 1
                continue

        if addEntry != 0:
            alllines.append(vHostFileName + "_access_log:" + vHostWebroot + ":" + vHostName + '\n')

        # rename the old file
        os.rename(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"], config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"] + '.bak')
        # open the destination file
        destination_file = open(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"], 'w')
        # write lines into file
        destination_file.writelines(alllines)
        # close the destination file
        destination_file.close()

    def SplitVHostList(self, alllines):
        """ Splits the values in the vHost.txt so that it
        can be used by other functions """
        for eachline in alllines:
            if eachline[0] == '#' or eachline[0] == '\n':
                continue
            else:
                eachline1 = re.split(':', eachline)
                eachline2 = eachline1[2]
                if eachline2[-1]=='\n' : eachline = eachline2[:-1]
                print eachline

        return eachline

    def SplitWebrootList(self, alllines):
        """ splitting the webroot from a list... :P """
        for eachline in alllines:
            if eachline[0] == '#':
                continue
            else:
                eachline1 = re.split(':', eachline)
                eachline2 = eachline1[1]
                if eachline2[-1]=='\n' : eachline = eachline2[:-1]
                print eachline

    def SplitAccessLogList(self, alllines):
        """ splitting the access_log from a list... :P """
        for eachline in alllines:
            if eachline[0] == '#':
                continue
            else:
                eachline1 = re.split(':', eachline)
                eachline2 = eachline1[0]
                if eachline2[-1]=='\n' : eachline = eachline2[:-1]
                print eachline

    def FormattedSplitURLWebroot(self, config, vHostTextList, searchCriteria):
        """ splitting url webroot something ... :P """
        # format the output into
        # URL = Webroot
        # ie web2.erikin.com = wwwroot
        
        ## DEBUGGING the value of vHostTextList
        if config['General']["debugLevel"] == '5':
            print "vHostTextList = ", vHostTextList
            
        vhostNewList = []
        for eachline in vHostTextList:
            ## DEBUGGING the value of eachline and eachline[0]
            if config['General']["debugLevel"] == '5':
                print "eachline = ", eachline
                print "eachline[0] = ", eachline[0]
                
            if eachline[0] == '#' or eachline[0] == '\n':
                continue
            else:
                eachline1 = re.split(':', eachline)                    
                url = eachline1[2]
                webroot = eachline1[1]
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print "eachline1 = ", eachline1
                    print "url = ", url
                    print "webroot = ", webroot

                if url[-1]=='\n':
                    eachline = url[:-1]
                    column1spacing = 30 - len(eachline)
                    eachline = eachline + " "*column1spacing + " | " + webroot
                    
                vhostNewList.append(eachline)
                
        ## DEBUGGING
        if config['General']["debugLevel"] == '5':
            print "searchCriteria = ", searchCriteria

        vhostNewList.sort()
        for line in vhostNewList:
            if searchCriteria == '':
                print line
            else:
                p = re.compile(searchCriteria)
                checkSearchCriteria = p.search(line)
                ## DEBUGGING
                if config['General']["debugLevel"] == '5':
                    print "checkSearchCriteria = ", checkSearchCriteria
                if checkSearchCriteria != None:
                    print line

    def OutputVhostList(self, apacheDict, utilityObject):
        """ Output the vHost list to STOUT """
        """ 10/12/05 -- this doesn't seem to be used... """
        """ 05/22/06 -- it is used by Htgroup.py """
        webroot = ""
        alllines = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"])
        # grab the list of virtual hosts
        print "\nChoose from this list of Virtual Hosts:\n"
        self.SplitVHostList(alllines)
	
        vHostName = raw_input("\nWhat virtual host do you want the web to be in? ")
        print vHostName
        if vHostName == "web2.erikin.com":
            webroot = "wwwroot"
            print "The vHost you chose was web2"
        else:
            print "The vHost you chose was ", vHostName

        # return webroot
        for webroot in alllines:
            if webroot[0] == '#' or webroot == '\n':
                continue
            else:
                webroot1 = re.split(':', webroot)
                webroot2 = webroot1[1]
                fqdn = webroot1[2]
                if fqdn[-1]=='\n' : fqdn = fqdn[:-1]
                if fqdn == vHostName:
                    webroot = webroot2
                    break
                    
	return webroot

    def EditApacheConf(self, config):
        """ Open specified conf files in an editor """
        # ask if the user would like to view the main apache conf file
        openMainApacheConf = raw_input("Edit the main Apache configuration file (ie httpd.conf)? [y/N] ")
        if openMainApacheConf == "":
            openMainApacheConf = "n"

        ## DEBUGGING (allows us to step through this application)
        if config['General']["debugLevel"] == '5':
            import pdb; pdb.set_trace()
            
        if openMainApacheConf == "y":
            openMainApacheConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfDir"] + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheGlobalConf"]
            os.system(openMainApacheConfCmd)

        # ask if the user would like to open a vhost as well
        openVHostConf = raw_input("Edit a virtual host configuration file? [Y/n]")
        if openVHostConf == "":
            openVHostConf = "y"

        if openVHostConf == "y":
            # print the possible conf files for the virtual hosts
            listVHostFilesCmd = config['General']["binPath"] + "ls " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"]
            os.system(listVHostFilesCmd)
            # get the url for the vHost
            print
            vHostUrl = ""
            while vHostUrl == "":
                vHostUrl = raw_input("URL of virtual host (ie www.erikin.com): ")

            vHostFileName = re.sub('\.', '_', vHostUrl)
            
            # get which vHost they would like to edit
            vHostType = ""
            print
            print "(1) http conf        (port 80)"
            print "(2) https conf       (port 443)"
            print "(3) publishing conf  (port 8080)"
            print "(4) http/https confs (port 80 AND port 443)"
            print "(5) all conf files   (port 80, port 443, AND port 8080)"
            print
            while vHostType == "":
                vHostType = raw_input("Configuration file(s): ")

            if vHostType == "1":
                openMainApacheVHostConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + ".conf"
                os.system(openMainApacheVHostConfCmd)
            elif vHostType == "2":
                openMainApacheVHostConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + "_ssl.conf"
                os.system(openMainApacheVHostConfCmd)
            elif vHostType == "3":
                openMainApacheVHostConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + "_publishing.conf"
                os.system(openMainApacheVHostConfCmd)
            elif vHostType == "4":
                openMainApacheVHostConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + ".conf " + vHostFileName + "_ssl.conf"
                os.system(openMainApacheVHostConfCmd)
            elif vHostType == "5":
                openMainApacheVHostConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheConfvHostDir"] + vHostFileName + ".conf " + vHostFileName + "_ssl.conf " + vHostFileName + "_publishing.conf"
                os.system(openMainApacheVHostConfCmd)
            
        # ask if we want to restart apache...
        restartApache = raw_input("Restart Apache? [Y/n] ")
        if restartApache == "":
            restartApache = "y"
        if restartApache == "y":
            self.ApacheCtl(config)
        else:
            print
            print "You will need to restart apache manually for any changes to take effect."
            print


    def EditPHPConf(self, config):
        """ Open specified conf files in an editor """
        openPHPConfCmd = config['General']["usrBinPath"] + "editor " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["phpConf"]
        os.system(openPHPConfCmd)
            
        # ask if we want to restart apache...
        restartApache = raw_input("Restart Apache? [Y/n] ")
        if restartApache == "":
            restartApache = "y"
        if restartApache == "y":
            self.ApacheCtl(config)
        else:
            print
            print "You will need to restart apache manually for any changes to take effect."
            print


    def EditHtaccess(self, config):
        """ Open specified htaccess files in an editor """
        # get the url for the vHost
        print
        vHostUrl = ""
        while vHostUrl == "":
            vHostUrl = raw_input("URL of virtual host (ie www.erikin.com/afrotc): ")

        splitVhostNestedWebroot = re.split('/', vHostUrl)
        # remove the fqdn from splitVhostNestedWebroot
        subFolders = "/".join(splitVhostNestedWebroot[1:])

        ## DEBUGGING
        if config['General']["debugLevel"] == '1':
            print "vHostUrl == ", vHostUrl
            print "splitVhostNestedWebroot == ", splitVhostNestedWebroot
            print "subFolders == ", subFolders
            
        # get the vhost.txt contents so that we can grab the webroot
        vhostContents = self.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"])

        # sort alphabetically
        vhostContents.sort()

        for line in vhostContents:
            p = re.compile(splitVhostNestedWebroot[0])
            checkVhostCriteria = p.search(line)
            ## DEBUGGING
            if config['General']["debugLevel"] == '1':
                print "checkVhostCriteria = ", checkVhostCriteria
            if checkVhostCriteria != None:
                matchLine = line
                matchLineList = re.split(':', matchLine)
                webroot = matchLineList[1]

        htaccessDir = config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["vHostRoot"] + webroot + "/" + subFolders + "/"
        
        print "We are editing files in: "
        print
        print htaccessDir
        print
            
        # get which file they would like to edit
        fileType = ""
        print
        print "(1) .htaccess"
        print "(2) .htaccess2"
        print "(3) both .htaccess files"
        print
        while fileType == "":
            fileType = raw_input(".htaccess file(s): ")

        if fileType == "1":
            openHtaccessCmd = config['General']["usrBinPath"] + "editor " + htaccessDir + ".htaccess"
            os.system(openHtaccessCmd)
        elif fileType == "2":
            openHtaccessCmd = config['General']["usrBinPath"] + "editor " + htaccessDir + ".htaccess2"
            os.system(openHtaccessCmd)
        elif fileType == "3":
            openHtaccessCmd = config['General']["usrBinPath"] + "editor " + htaccessDir + ".htaccess*"
            os.system(openHtaccessCmd)

            
            
    def ApacheCtl(self, config):
        """ Restarts Apache """
	# restart webFarmAdminMachine apache server, (this may also be a single instance of apache),
        # to verify that the configuration is ok
        apacheCmd = raw_input("start|stop|reload|reload-modules|force-reload|[RESTART] Apache? ")
        if apacheCmd == "":
            apacheCmd = "restart"
            
	restartApacheOnAdmin = config['General']["usrBinPath"] + "ssh " + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["adminMachine"] + " '" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheInitScriptPath"] + " " + apacheCmd + "'"
        
        ## DEBUGGING
        if config['General']["debugLevel"] == '1':
            print "\nrestartApacheOnAdmin == ", restartApacheOnAdmin

	os.system(restartApacheOnAdmin)
        
        # if len(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["nodes"] is 0, then there are _no_ web farm node machines
        if len(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["nodes"]) != 0:
            # ask if the previous command executed with no errors
            print
            print "Do NOT restart the node servers if the previous command returned any errors!!!"
            print
            restartOk = raw_input("Should I restart the node servers as well? [Y/n] ")
            if restartOk == "":
               restartOk = "y"
               
            # if the user has authorized us to restart the node servers, then we call self.NodeApacheCtl()
            if restartOk == "y":
               #self.NodeApacheCtl(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']], config, apacheCmd)
               self.NodeApacheCtl(config, apacheCmd)
            else:
                print
                print "You will need to restart the web farm nodes manually for any changes to take effect."
                print

    def NodeApacheCtl(self, config, apacheCmd):
        """ Restarts Apache """
	# restart webFarmNodeMachines apache server, (this will restart all node machines with the same
        # apacheCmd as chosen in ApacheCtl() ), to verify that the configuration is ok
        if apacheCmd == "":
            apacheCmd = raw_input("start|stop|reload|reload-modules|force-reload|[RESTART] Apache? ")
            
        if apacheCmd == "":
            apacheCmd = "restart"

        for node in config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["nodes"]:
            restartApacheOnNode = config['General']["usrBinPath"] + "ssh " + node + " '" + config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["apacheInitScriptPath"] + " " + apacheCmd + "'"
        
            ## DEBUGGING
            if config['General']["debugLevel"] == '5':
                print "\nrestartApacheOnNode == ", restartApacheOnNode

            os.system(restartApacheOnNode)
        


    def VHostSearchPrompt(self):
        """ Generate VHost Search Prompt w/ help """
        help = 'h'
        while help == 'h':
            filter = raw_input("VHost Search: (h => help, q => quit) ")
            if filter == '':
                filter = 'a'
            if filter == 'h':
                print "\VHost Search:\n"
                print
                print "Simply hit <ENTER> to view all virtual hosts"
                print
                print "www.erikin.com => limits search results to www.erikin.com"
                print "*erikin.com   => limits search results to all erikin.com domains"
                print "*laurabushfoundation*  => limits search results to all laurabushfoundation domains"
                print "--------------------\n"
            elif filter == 'a':
                # view all
                filter = ''
                break
            elif filter == 'q':
                break
            else:
                help = ''               
                break

        return filter


    def PrintVhost(self, config, utilityObject):
        """
        
        Find out if the user wants us to spit out a formatted list of virtual hosts
        If viewVhost == 'y' grab the contents of the VHost file and spit out in
        following format:
        
        www.test7.example.com             | www_test7_example_com
        
        """
        viewVhost = raw_input("Would you like to view existing virtual hosts? (y/[n])  ")
        if viewVhost == "":
            viewVhost = "n"
            
        if viewVhost == 'y':
            # ask the user if they would like to limit their search
            searchCriteria = self.VHostSearchPrompt()

            # grab the list of virtual hosts
            vHostTextList = utilityObject.GrabTextList(config['Apache']['Server' + config['Session']['Apache']['CurrentServer']]["pathToVhostFile"])            
            print "\nThese are the existing Virtual Hosts:\n"
            self.FormattedSplitURLWebroot(config, vHostTextList, searchCriteria)

            print "\nNOTE: Format is FQDN => webroot.  Webroots should be viewed as: /var/www\n"
            print "If the virtual host exists in this list, but is not the correct virtual host"
            print "stop here <CTRL>-c, and think about what is going on.  I don't know what will happen"
            print "if you create a vhost over the top of an existing one.  (Hopefully, nothing)\n"

